var hostIpManager = (function () {
    var map = {};
    var hostIpMap = {};

    function getHostFromURL(url) {
        var start = url.indexOf("//") + 2;
        if (start == 1)return null;
        url = url.substring(start);
        if (url.indexOf("/") >= 0) {
            return url.substring(0, url.indexOf("/"));
        }
        return url;
    }

    chrome.webRequest.onCompleted.addListener(function (detail) {
        var tabId = detail.tabId;
        if (!map.hasOwnProperty(tabId)) {
            map[tabId] = {};
        }
        var ip = detail.ip;
        if (ip === undefined) {
            return;
        }
        var url = detail.url;
        var host = getHostFromURL(url);
        if (host != null) {
            map[tabId][host] = ip;
            hostIpMap[host] = ip;
        } else {
            console.error("解析Host失败", url);
        }
    }, {urls: ["<all_urls>"]});

    return {
        clean: function () {
            map = {};
            hostIpMap = {};
        },
        getMap: function () {
            return map;
        },
        getHostIpMap: function () {
            return hostIpMap;
        },
        getTabIdMap: function (tabId) {
            return map[tabId];
        },
        getIpByUrl: function (tabId, url) {
            var host = getHostFromURL(url);
            return map[tabId][host];
        }
    }
})();

// 清理 Host 缓存和现有 Socket 链接
(function () {
    chrome.browserAction.onClicked.addListener(function (tab) {
        chrome.tabs.query({}, function (tabs) {
            hostIpManager.clean();
            chrome.tabs.create({url: 'chrome://net-internals/', active: false}, function (tab) {
                var tabId = tab.id;
                chrome.tabs.executeScript(tabId, {file: "flush.js"}, function () {
                    chrome.tabs.remove(tabId);
                });
            });
        });
    });
})();

// 右键菜单
(function () {
    chrome.contextMenus.create({
        "type": "normal",
        "title": "显示/隐藏 IP",
        "onclick": function (info, tab) {
            var tabId = tab.id;
            var ip = hostIpManager.getIpByUrl(tabId, tab.url);
            chrome.tabs.sendMessage(tabId, {
                "ip": ip
            });
        }
    });
    chrome.contextMenus.create({
        "type": "normal",
        "title": "查看所有 IP",
        "onclick": function (info, tab) {
            var tabId = tab.id;
            chrome.tabs.create({url: 'host.html', active: false});
        }
    })
})();

(function () {
    chrome.runtime.onConnect.addListener(function (port) {
        var hostIpMap = hostIpManager.getHostIpMap();
        chrome.tabs.sendMessage(port.sender.tab.id, hostIpMap);
    });
})();